<template>
  <CDialog
    class="connect-factory-dialog"
    title="关联工厂/组织"
    v-model:visible="dialogVisible"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
    :loading="loading"
    size="small"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="工厂名称" prop="plantName">
            <el-input v-model="formData.plantName" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="工厂ID" prop="plantId">
            <el-input v-model="formData.plantId" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="关联组织" prop="organizationCode">
            <el-tree-select
              ref="orgTreeRef"
              check-strictly
              v-model="formData.organizationCode"
              :data="orgTreeData"
              :multiple="false"
              collapse-tags
              collapse-tags-tooltip
              :show-checkbox="false"
              filterable
              default-expand-all
              :props="treeSelectProps"
              placeholder="请选择"
              style="width: 100%"
              @change="handleChange"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </CDialog>
</template>
<script lang="ts">
export default {
  name: 'ConnectFactoryDialog'
};
</script>
<script lang="ts" setup>
import { defineProps, withDefaults, defineEmits, computed, ref, watch, reactive } from 'vue';
import { CDialog } from '@/components/CDialog';
import { useMessage } from '@/hooks/useMessage';
import { getOrganizationTreeByUser } from '@/apis/system/organization';
import { GetOrganizationTreeResult } from '@/apis/system/model/organizationModel';
import { store } from '@/store';
import { rules } from './rules';
import { postPlantAdd } from '@/apis/system/config/factoryWorkshopMeterSet';

interface ConnectFactoryDialogProps {
  visible: boolean;
}
const props = withDefaults(defineProps<ConnectFactoryDialogProps>(), {
  visible: false
});
const emit = defineEmits(['update:visible', 'refresh']);

const { createMessage } = useMessage();

const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emit('update:visible', val);
  }
});
watch(
  () => dialogVisible.value,
  visible => {
    if (!visible) {
      // 关闭时清空数据
      handleClear();
    } else {
      // 打开时初始化新数据
      initVisible();
    }
  }
);

const formRef = ref();
const loading = ref(false);
const formData = reactive({
  plantName: '',
  plantId: '',
  organizationCode: '',
  organizationName: ''
});

// 提交按钮
function handleConfirm() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      submitTaskReq();
    }
  });
}

// 请求接口
async function submitTaskReq() {
  try {
    loading.value = true;
    const params = {
      plantId: formData.plantId,
      plantName: formData.plantName,
      organizationCode: formData.organizationCode,
      organizationName: formData.organizationName
    };
    await postPlantAdd(params);
    createMessage.success('关联工厂/组织成功');
    dialogVisible.value = false;
    loading.value = false;
    emit('refresh');
  } catch (error) {
    loading.value = false;
  }
}

// 关闭时清空数据
function handleClear() {
  loading.value = false;
  formRef.value?.resetFields();
  formData.plantName = '';
  formData.plantId = '';
  formData.organizationCode = '';
}

// 打开时初始化
async function initVisible() {
  handleClear();
  getOrgTreeByInventoryYearReq();
}

const orgTreeRef = ref();
const orgTreeData = ref<GetOrganizationTreeResult[]>([]);
const treeSelectProps = {
  label: 'organizationName',
  disabled: (data: any) => {
    return !data.enable;
  }
};
/**
 * 选中时，获取组织名称
 */
function handleChange(val: string) {
  const { data = {} } = orgTreeRef.value?.getNode(val);
  formData.organizationName = data?.organizationName || '';
}
/**
 * 获取组织边界树
 */
async function getOrgTreeByInventoryYearReq() {
  try {
    const userId = store.state.user.userInfo.userId;
    const res = await getOrganizationTreeByUser(userId);
    orgTreeData.value = handleGetTreeByOrgCode(res);
  } catch (error) {
    console.log('error', error);
    orgTreeData.value = [];
  }
}
/**
 * 遍历树，增加value
 */
function handleGetTreeByOrgCode(sourceTree: GetOrganizationTreeResult[]) {
  for (let i = 0; i < sourceTree.length; i++) {
    const item = sourceTree[i];
    Object.assign(item, {
      value: item.organizationCode
    });
    if (item.children?.length) {
      handleGetTreeByOrgCode(item.children);
    }
  }
  return sourceTree;
}
</script>
